import React, { useState, useEffect } from "react";
import { Button, Form, Input, Select, DatePicker, message, Spin } from "antd";
import '../components.css';
import RepaymentScheduleService from "../../services/RepaymentScheduleService";
import { useParams, useNavigate } from 'react-router-dom'; // 修改：确保已导入 useParams
import dayjs from 'dayjs';
import { CloseCircleOutlined, CaretUpOutlined } from '@ant-design/icons';

const { Option } = Select;

export default function UpdateRepaymentSchedule() {
    const [formData, setFormData] = useState({
        contractNumber: "",
        customerName: "",
        period: "",
        totalPeriods: "",
        principal: "",
        dueDate: null,
        status: "PENDING"
    });
    
    const [loading, setLoading] = useState(false);
    const navigate = useNavigate();
    
    const statusOptions = [
        { value: 'PENDING', label: '未到期' },
        { value: 'PAID', label: '已支付' },
        { value: 'OVERDUE', label: '已逾期' }
    ];
    
    // ===== 主要修改部分 =====
    // 使用 useParams 直接获取路由参数
    const { id } = useParams(); // 替换原来的 location 方式
    // ======================

    const updateRepaymentSchedule = (e) => {
        e.preventDefault();
        setLoading(true);

        if (!formData.dueDate) {
            message.error('请选择到期日');
            setLoading(false);
            return;
        }

        const repaymentSchedule = {
            contractNumber: formData.contractNumber,
            customerName: formData.customerName,
            period: parseInt(formData.period || "0"),
            totalPeriods: parseInt(formData.totalPeriods || "0"),
            principal: parseFloat(formData.principal || "0") || 0,
            dueDate: formData.dueDate.format('YYYY-MM-DD'), // 修复：格式应为大写 YYYY
            status: formData.status
        };
        
        RepaymentScheduleService.updateRepaymentSchedule(id, repaymentSchedule)
            .then(response => {
                message.success('还款计划更新成功!');
                navigate('/repaymentschedulelist');
            })
            .catch(error => {
                console.error('更新失败:', error);
                message.error('更新还款计划失败: ' + (error.response?.data?.message || error.message));
            })
            .finally(() => {
                setLoading(false);
            });
    };

    useEffect(() => {
        setLoading(true);
        RepaymentScheduleService.getRepaymentScheduleById(id)
            .then(response => {
                const data = response.data;
                setFormData({
                    contractNumber: data.contractNumber || "",
                    customerName: data.customerName || "",
                    period: data.period ? data.period.toString() : "",
                    totalPeriods: data.totalPeriods ? data.totalPeriods.toString() : "",
                    principal: data.principal ? data.principal.toString() : "",
                    dueDate: data.dueDate ? dayjs(data.dueDate) : dayjs(null),
                    status: data.status || "PENDING"
                });
            })
            .catch(error => {
                console.error('加载数据失败:', error);
                message.error('加载还款计划数据失败');
            })
            .finally(() => {
                setLoading(false);
            });
    }, [id]);

    const handleInputChange = (field, value) => {
        setFormData(prev => ({ ...prev, [field]: value }));
    };

    return (
        <Spin spinning={loading}>
            <div className='UpdateRepaymentSchedule'>
                <div className="title" style={{ paddingBottom: '30px' }}>更新还款计划</div>
                
                <Form
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 15 }}
                    style={{ marginLeft: '2%' }}
                    autoComplete="off"
                >
                    <Form.Item label="合同编号">
                        <Input 
                            value={formData.contractNumber || ""}
                            readOnly 
                        />
                    </Form.Item>
                    
                    <Form.Item label="客户名称">
                        <Input 
                            value={formData.customerName || ""}
                            onChange={(e) => handleInputChange('customerName', e.target.value)}
                            placeholder="请输入客户名称" 
                        />
                    </Form.Item>
                    
                    <Form.Item label="当前期数">
                        <Input 
                            type="number" 
                            min={1} 
                            value={formData.period || ""}
                            onChange={(e) => handleInputChange('period', e.target.value)}
                            placeholder="请输入当前期数" 
                        />
                    </Form.Item>
                    
                    <Form.Item label="总期数">
                        <Input 
                            type="number" 
                            min={1} 
                            value={formData.totalPeriods || ""}
                            onChange={(e) => handleInputChange('totalPeriods', e.target.value)}
                            placeholder="请输入总期数" 
                        />
                    </Form.Item>
                    
                    <Form.Item label="本金">
                        <Input 
                            prefix="¥" 
                            value={formData.principal || ""}
                            onChange={(e) => handleInputChange('principal', e.target.value)}
                            placeholder="请输入本金金额" 
                        />
                    </Form.Item>
                    
                    <Form.Item label="到期日">
                        <DatePicker 
                            format="YYYY-MM-DD" 
                            style={{ width: '100%' }} 
                            value={formData.dueDate}
                            onChange={(date) => handleInputChange('dueDate', date)}
                            disabledDate={(current) => current && current < dayjs().startOf('day')}
                        />
                    </Form.Item>
                    
                    <Form.Item label="状态">
                        <Select 
                            value={formData.status || "PENDING"}
                            onChange={(value) => handleInputChange('status', value)}
                            placeholder="请选择还款状态"
                        >
                            {statusOptions.map(option => (
                                <Option key={option.value} value={option.value}>
                                    {option.label}
                                </Option>
                            ))}
                        </Select>
                    </Form.Item>
                    
                    <Form.Item
                        wrapperCol={{ offset: 5, span: 16 }}
                        style={{ marginTop: '50px' }}
                    >
                        <Button 
                            type="primary" 
                            onClick={updateRepaymentSchedule}
                            icon={<CaretUpOutlined style={{ marginRight: "2px" }} />}
                        >
                            更新
                        </Button>
                        <Button 
                            type='danger' 
                            style={{ marginLeft: "25px" }} 
                            icon={<CloseCircleOutlined style={{ marginRight: "2px" }} />}
                            onClick={() => navigate('/repaymentschedulelist')}
                        >
                            关闭
                        </Button>
                    </Form.Item>
                </Form>
            </div>
        </Spin>
    )
}